package lunchy.mvc.models;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import lunchy.data.classes.CLunchyOrder;
import lunchy.data.classes.CLunchyOrderItem;
import lunchy.data.classes.CLunchyXMLOrderDAO;
import lunchy.data.interfaces.ILunchyMenu;
import lunchy.data.interfaces.ILunchyMenuGroup;
import lunchy.data.interfaces.ILunchyMenuItem;
import lunchy.data.interfaces.ILunchyOrder;
import lunchy.data.interfaces.ILunchyOrderDAO;
import lunchy.main.CLunchyApplication;

public class CLunchyMenuModel
{
	private ILunchyMenu menu;
	private Map<ILunchyMenuItem, Integer> saveItemsMap;
	
	public CLunchyMenuModel()
	{
		menu = CLunchyApplication.getInstance().dataConnection.getMenuDAO().getActiveMenuItems();
		saveItemsMap = new HashMap<ILunchyMenuItem, Integer>();
	}

	public ArrayList<ILunchyMenuGroup> getMenuGroups()
	{
		return menu.getMenuGroups();
	}
	
	public void reloadMenu()
	{
		menu = CLunchyApplication.getInstance().dataConnection.getMenuDAO().getActiveMenuItems();
	}
	
	public void AddOrUpdateItemInCurrentOrder(ILunchyMenuItem item, Integer count)
	{
		if(saveItemsMap.containsKey(item))
			saveItemsMap.remove(item);
		
		if(count > 0)
			saveItemsMap.put(item, count);
	}
	
	public boolean saveOrder()
	{
		CLunchyApplication.getInstance().debug("[CLunchyMenuModel] Saving order:");
		
		ILunchyOrderDAO orderConnection = CLunchyApplication.getInstance().dataConnection.getOrderDAO();
		ILunchyOrder currentOrder = new CLunchyOrder();
		
		Set<ILunchyMenuItem> menuItems = saveItemsMap.keySet();
		
		for (ILunchyMenuItem item : menuItems)
		{
			if(saveItemsMap.get(item) > 0)
			{
				CLunchyApplication.getInstance().debug("[CLunchyMenuModel] Item " + item.getName() + " = " + saveItemsMap.get(item));
				currentOrder.addItemToOrder(new CLunchyOrderItem(item, saveItemsMap.get(item)));
			}
		}
		
		orderConnection.addOrder(currentOrder);
		
		return true;
	}
}
